package session.TX;

import entity.TransactionEntry;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import entity.Users;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Random; 

/**
 *
 * @author TWD
 */
@Stateless
public class LuckyDrawSB implements LuckyDrawSBRemote{

    @PersistenceContext
    private EntityManager em;
    List<String> email = new ArrayList();
    String[] user = new String[3];
    
    public LuckyDrawSB(){
    }
    
    public void sendEmail(List<String> email){
        
        Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.socketFactory.port", "465");
	props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.port", "465");
 
	Session session = Session.getInstance(props, new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("foodsage.tcube@gmail.com","3332720twd");
				}
			});
        session.setDebug(true);
 
	try{        
            for(int x=0; x<email.size(); x++){
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("foodsage.tcube@gmail.com"));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.get(x)));
		message.setSubject("FoodSage.sg Monthly Lucky Draw Winner");
		message.setText("Dear " + email.get(x) + "," + "\n\n CONGRATULATIONS! \n\n You have been chosen for our monthly lucky draw winner.");
		Transport.send(message);
            } 
	}catch (MessagingException e){
		throw new RuntimeException(e);
	}
        System.out.print("Email Sent to Stakeholder");
    }
    
    public List<String> generateLuckyDrawWinners(int month, int year){
        
        int numberOfUsers;
        Query q1 = em.createQuery("SELECT c FROM TransactionEntry c");
        List resultList = q1.getResultList();
        List resultList2 = new ArrayList<TransactionEntry>();
        TransactionEntry transaction;
        //System.out.println("#######" + month);
        //System.out.println("#######" + year);
        //extracting the desired transaction records.
        for (Object o : resultList){
            transaction = (TransactionEntry)o;
            //System.out.println(transaction.getTime_stamp().get(Calendar.MONTH) + 1);
            //System.out.println(transaction.getTime_stamp().get(Calendar.YEAR));
            if(((transaction.getTime_stamp().get(Calendar.MONTH)) == (month-1)) && (transaction.getTime_stamp().get(Calendar.YEAR) == year)){
                resultList2.add(transaction);
            }
        }
        numberOfUsers = resultList2.size();   
        System.out.println("############*********** " + numberOfUsers);
        if(numberOfUsers == 0){
            return null;
        }
        
        //Random Number Generation
        ArrayList randNum = new ArrayList();
        ArrayList userName = new ArrayList();
        Random rand = new Random(); 
        int randomNumber;
        
       for(int x=0; x<3; x++){
            randomNumber = rand.nextInt(numberOfUsers);
            transaction = (TransactionEntry)resultList2.get(randomNumber);
            while(userName.contains(transaction.getCustomerEmail())){
                randomNumber = rand.nextInt(numberOfUsers);
                transaction = (TransactionEntry)resultList2.get(randomNumber);
            }
            userName.add(transaction.getCustomerEmail());
       }
       return userName;
    }
    
    public List<Users> generateUserInformation(List<String> list){
        List<Users> user = new ArrayList<Users>();
        Users userTest;
        for(int x=0; x<list.size(); x++){
            Query q1 = em.createQuery("SELECT c FROM Users c WHERE c.email = :paramArea");
            q1.setParameter("paramArea", list.get(x));
            List resultList = q1.getResultList();
            Object o = resultList.get(0);
            Users myUser = (Users)o;
            user.add(myUser);
        }
        for(int y=0; y<user.size(); y++){
            userTest = user.get(y);
            userTest.setLoyaltypoint((userTest.getLoyaltypoint() + 1000));
        }
        sendEmail(list);
        return user;
    }
}
